class ManagementYuiController < ApplicationController
  layout "management_yui"
  before_filter :getId
  def main
    @userInfos = UserInfo.find(:all)
    @users = User.paginate :page => params[:page], :per_page => 3, :order => "nickname"
    respond_to do |format|
      format.html {render :template=> "/management/users/index"}
    end
  end
  
  def detail
    begin
      @user = User.find(params[:id])
      @user_detail = @user.user_detail || UserDetail.new(:user_id =>params[:id])
#      flash[:detail_need] = @user.id
    #puts flash[:detail_need]
    rescue ActiveRecord::RecordNotFound
#      @user_detail = UserDetail.new(:user_id =>params[:id])
      flash[:notice] = '用户没有找到'    
    end  
    respond_to do |format|
      format.html { render :template=> '/management/users/detail'}  
      format.xml  { render :xml => @users }
    end
  end
  
  def edit  
    @user = User.find(params[:id])
    @user_info = UserInfo.find(:first,:conditions=>["user_id=?",@user.id]) 
    respond_to do |format|
      format.html { render :template=> '/management/users/edit'}  
      format.xml  { render :xml => @users }
    end    
  end
  
  
  def update_userinfo
    @user = User.find(params[:user][:id],:include =>'user_info') 
    @user_info = UserInfo.find(:first,:conditions=>["user_id=?",@user.id]) 
    
    #Validate start
    #    session[:user_info_errors]=nil
    #    @user_info.errors.clear 
    if ((params[:user][:email]=~(/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/))==nil)&&(params[:user][:email]!="")
      @user_info.errors.add("emailError"," 邮箱不合法")
    end
    if ((params[:user_info][:postalcode]=~(/[1-9]\d{5}(?!\d)/))==nil)&&(params[:user_info][:postalcode]!="")
      @user_info.errors.add("post"," 邮编不合法")
    end
    if ((params[:user_info][:telephone]=~(/\d{3}-\d{8}|\d{4}-\d{7}/))==nil)&&((params[:user_info][:telephone]=~(/[1-9][0-9]{10,}/))==nil)&&(params[:user_info][:telephone]!="")
      @user_info.errors.add("phone"," 电话号码不合法 ")
    end
    
    if @user_info.errors.length >0
      respond_to do |format|
        session[:user_info_errors]=@user_info
        format.html {redirect_to(:controller=>"management_yui",:action =>"edit",:id=>@user_info.user_id)}
      end
    else
      #Validate end
      respond_to do |format|
        if @user.update_attributes(params[:user])&&@user.user_info.update_attributes(params[:user_info])
          flash[:notice] = '基本详细更新成功.'
          format.html { redirect_to(:controller=>"home", :action=>"welcome") }
          format.xml  { head :ok }
        else
          format.html { render :action => "edit" }
          format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
        end
      end
    end
  end  

  
  private
  def getId
    @user = User.find_by_id(session[:user_id])
  end
end